import { Request, Response, NextFunction } from 'express'
import { Redis } from 'ioredis'

const redis = new Redis(process.env.REDIS_URL!)

// 速率限制检查
export const rateLimit = async (req: Request, action: string, limit: number): Promise<boolean> => {
    const key = `ratelimit:${action}:${req.user?.id || req.ip}`
    const current = await redis.incr(key)

    // 设置过期时间（1分钟）
    if (current === 1) {
        await redis.expire(key, 60)
    }

    return current <= limit
}

// 速率限制中间件
export const rateLimitMiddleware = (action: string, limit: number) => {
    return async (req: Request, res: Response, next: NextFunction) => {
        try {
            if (await rateLimit(req, action, limit)) {
                next()
            } else {
                res.status(429).json({ error: '请求过于频繁，请稍后再试' })
            }
        } catch (error) {
            next(error)
        }
    }
} 